import koa from "koa"
import { Sequelize,DataTypes } from "sequelize"
import cors from "@koa/cors"
import bodyparsser from "koa-bodyparser"
import Router from "koa-router"

let app = new koa()
let router = new Router() 
let appPort = 7878

let sequelize = new Sequelize("dbs","root","123456",{
    dialect:"mysql",
    host:"localhost"
})
let Book = sequelize.define("books",{
    bookName:DataTypes.STRING,
    author:DataTypes.STRING
})
await sequelize.sync({force:true})
Book.bulkCreate([
    {
        bookName:"我有一个叮咚鸡",
        author:"叮咚鸡"
    },
    {
        bookName:"重生之我是大狗叫",
        author:"大狗叫"
    },
    {
        bookName:"见杠马传",
        author:"见杠马"
    }
])

app.use(cors())
app.use(bodyparsser())

router.get("/books",async(ctx)=>{
let obj = await Book.findAll()
ctx.body={
    code:1000,
    data:obj,
    msg:"查询成功"
}
})
router.get("/books/:id",async(ctx)=>{
    let id = ctx.params.id||0
    let obj = await Book.findByPk(id)
    ctx.body={
        code:1000,
        data:obj,
        msg:"单项查询成功"
    }
})
router.post("/books",async(ctx)=>{
    let txt = ctx.request.body;
    let obj = await Book.create(txt)
    ctx.body={
        code:1000,
        data:obj,
        msg:"添加成功"
    }
})
router.put("/books",async(ctx)=>{
    
})
router.delete("/books/:id",async(ctx)=>{
    let id = ctx.params.id||0
    let obj = await Book.destroy({
        where:{id}
    })
    ctx.body={
        code:1000,
        data:obj,
        msg:"删除成功"
    }
})

app.use(router.routes())
app.listen(appPort)
console.log(`地址位于：http://localhost:${appPort}`);
